package com.platform.comm.web.results;

import lombok.Data;
import org.springframework.data.domain.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * Json result view: { total: <i>X</i>, rows: [...] }
 *
 * @author coder
 */
@Data
public class PageListDto<E> implements Serializable {

    private long total = 0;

    private List<E> rows = new ArrayList<>();

    public PageListDto() {
    }

    public PageListDto(List<E> rows) {
        if (rows != null) {
            this.total = rows.size();
            this.rows = rows;
        }
    }

    public PageListDto(List<E> rows, long total) {
        if (rows != null) {
            this.rows = rows;
        }
        this.total = total;
    }

    public static <E> PageListDto<E> empty() {
        PageListDto<E> result = new PageListDto<>();
        result.total = 0;
        result.rows = Collections.emptyList();

        return result;
    }

    public static <E> PageListDto<E> of(Page<E> page) {
        if (Objects.isNull(page)) {
            return empty();
        }

        PageListDto<E> result = new PageListDto<>();
        result.total = page.getTotalElements();
        result.rows = page.getContent();

        return result;
    }

    public static <E> PageListDto<E> of(PageListJsonResult<E> page) {
        if (Objects.isNull(page)) {
            return empty();
        }

        PageListDto<E> result = new PageListDto<>();
        result.total = page.getTotal();
        result.rows = page.getRows();

        return result;
    }

    public static <T> Page<T> toPage(PageListDto<T> pageListJsonResult) {

        return new PageImpl<>(pageListJsonResult.rows, PageRequest.of(0, 1), pageListJsonResult.total);
    }
}
